from scrapy.cmdline import execute
import pymongo
import sys
import os
import tkinter
import matplotlib.pyplot as plt

def runspider():
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    execute(["scrapy", "crawl", "zhihu"])


def mongodblink():
    client = pymongo.MongoClient('mongodb://localhost:27017/')
    db = client.zhihu
    collection = db.users
    return collection


def runspiders():
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    execute(["scrapy", "crawl", "zhihu"])


def GenderBar():
    collection = mongodblink()
    unknow = collection.find({'gender':-1}).count()
    female = collection.find({'gender':0}).count()
    male = collection.find({'gender':1}).count()
    name_list = ['unknow', 'female', 'male']
    num_list = [unknow, female, male]
    print(unknow, female, male)
    plt.bar(name_list, num_list)
    plt.show()


def GenderPie():
    collection = mongodblink()
    unknow = collection.find({'gender':-1}).count()
    female = collection.find({'gender':0}).count()
    male = collection.find({'gender':1}).count()
    name_list = ['unknow', 'female', 'male']
    num_list = [unknow, female, male]
    plt.axes(aspect=1)
    plt.pie(x=num_list, labels=name_list, autopct='%3.1f %%',
            shadow=True, labeldistance=1.1, startangle=90, pctdistance=0.6
            )
    plt.show()



def main():
    collection = mongodblink()
    top = tkinter.Tk()
    top.geometry("300x200")
    top.title("知乎用户分析")
    totaltext = "用户数据共有"+str(collection.find({}).count())+"条"

    spider = tkinter.Button(text="开始爬取", command=runspider)
    title = tkinter.Label(text="知乎用户分析" )
    total = tkinter.Label(text=totaltext)
    genderTitle = tkinter.Label(text="知乎用户男女比例")
    BarBt = tkinter.Button(text="显示柱状图", command=GenderBar)
    PieBt = tkinter.Button(text="显示饼状图", command=GenderPie)

    spider.pack()
    title.pack()
    total.pack()
    genderTitle.pack()
    BarBt.pack()
    PieBt.pack()
    top.mainloop()


if __name__ == '__main__':
    main()

